import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;

@Slf4j
public class Test21 {

    public static void main(String[] args) {
        MessageQueue queue = new MessageQueue(2);
        for (int i = 0; i < 3; i++) {
            int id = i;
            new Thread(() -> {
                queue.put(new Message(id, "消息" + id));
            }, "生产者" + i).start();
        }

        new Thread(() -> {
            try {
                while (true) {
                    Thread.sleep(1000);
                    Message message = queue.take();
                    log.info("消费消息：{}", message);
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }, "消费者").start();
    }

}


@Slf4j
// 消息队列类 java线程之间通信
class MessageQueue {

    // 消息队列集合
    private LinkedList<Message> list = new LinkedList<>();
    // 队列容量
    private int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    public Message take() {
        synchronized (list) {
            while (list.isEmpty()) {
                try {
                    log.info("队列为空，等待");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 从队列头部取出消息返回
            // 队列不满了，唤醒所有在put方法等待的线程
            Message message = list.removeFirst();
            log.info("取出消息：{}", message);
            list.notifyAll();
            return message;
        }
    }

    // 存入消息
    public void put(Message message) {
        synchronized (list) {
            while (list.size() == capacity) {
                try {
                    log.info("队列已满，等待");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.addLast(message);
            log.info("存入消息：{}", message);
            // 队列不空了，唤醒所有再take方法等待的线程
            list.notifyAll();
        }
    }

}


final class Message {
    private int id;
    private Object value;

    public Message(int id, Object value) {
        this.id = id;
        this.value = value;
    }

    public int getId() {
        return id;
    }

    public Object getValue() {
        return value;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", value=" + value +
                '}';
    }
}
